#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Project: devops
#  Author: an00
#  Create: 2018/8/4 11:24


from rest_framework import serializers
from business.models import Business


class BusinessSerializer(serializers.ModelSerializer):

    def validate_pid(self, pid):
        if pid > 0:
            try:
                business_obj = Business.objects.get(pk=pid)
                if business_obj.pid != 0:
                    return serializers.ValidationError('上级业务线错误')
            except Business.DoesNotExist:
                return serializers.ValidationError('上级业务线不存在')
            return pid
        else:
            return 0

    @staticmethod
    def get_user_response(user_queryset):
        result = []
        for user in user_queryset:
            result.append({
                "id": user.id,
                "username": user.username,
                "name": user.name,
                "email": user.email
            })
        return result

    def to_representation(self, instance):
        """
        将业务线的接口人信息返回前端
        """
        result = super(BusinessSerializer, self).to_representation(instance)
        result["dev_interface"] = self.get_user_response(instance.dev_interface.all())
        result["op_interface"] = self.get_user_response(instance.op_interface.all())
        return result

    def update(self, instance, validated_data):
        """
        更新
        """
        instance.name = validated_data.get('name', instance.name)
        instance.dev_interface = validated_data.get("dev_interface", instance.dev_interface)
        instance.op_interface = validated_data.get("op_interface", instance.op_interface)
        instance.letter = validated_data.get('letter', instance.letter)
        return instance

    class Meta:
        model = Business
        fields = '__all__'
